<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Item extends CI_Controller {
    
    private $datacard = array();
        
    function __construct(){
            parent::__construct();
            $this->load->model('Item_model');
            //$this->output->enable_profiler(TRUE);
            
        }
        public function index()
        {
                $data = array('content' => 'Дашбоард, в будущем');
               // print_r($data);
                $this->load->view('MasterPage', $data);
        }
        /**
         * Карточка товара
         * @param int $id Код предмета
         */
        public function card($id)
        {
            $page = array();
            $this->Item_model->InitCard($id);
            if ($this->Item_model->error == NULL)
            {
                $data = array(
                    'card'      => $this->Item_model->card,
                    'traffic'   => $this->Item_model->traffic,
                    'whereIt'   => $this->Item_model->whereIt,
                );
                $page['content'] = $this->load->view('Items/ItemCard', $data, true);
            }
            else
                $page['content'] = $this->Item_model->error;
            $this->load->view('MasterPage', $page);
        }
        /**
         * Передвижение товара
         * @param type $id код передвигаемого предмета
         */
        public function move($sklad = null, $id = null)
        {
            $page = array();
            $this->load->helper('form');
            $this->load->library('form_validation');
            
            
            if(isset($id) && isset($sklad))
            {
                //$this->Item_model->InitCard($id);
                //data for view
                $this->Item_model->InitMove($id, $sklad);
                $this->datacard = array(
                    'card'      => $this->Item_model->card,
                    'traffic'   => $this->Item_model->traffic,
                    'whereIt'   => $this->Item_model->whereIt,
                    'aSklad'    => $this->Item_model->allowedSklads,
                    'fromSklad' => $this->Item_model->fromSklad
                );
               // print_r($this->datacard);
                $this->form_validation->set_rules('count','Кол-во', 'trim|required|max_lenght[10]|numeric|callback_checkMax');
                $this->form_validation->set_rules('comment','Комментарий', 'trim|required|max_lenght[150]');

                if ($this->form_validation->run() == FALSE)
                {
                    $page['content'] = $this->load->view('Items/ItemMove', $this->datacard, TRUE);
                }
                else
                {
              
                    $obj = $this->Objects_model->GetObject(array('id' => $this->input->post('object_id')));
                    $data = array(
                        'itemId'        => $id,
                        'traffic'       => 0, //уменьшение это 0 прибавление это 1
                        'count'         => $this->input->post('count'),
                        'comments'      => $this->input->post('comment'),
                        'sklad'         => array(
                            'fromObj'       => $this->input->post('fromObj'),
                            'toObj'         => $this->input->post('object_id'),
                            'FromSkladAlt'  => $sklad,
                            'ToSkladAlt'    => $obj['alt_name']
                        )
                    );
                    $this->Item_model->SaveMove($data);
                    redirect('item/card/'.$id);
                }        
            }
            else
                $page['content'] = "Не верный код предмета";
            $this->load->view('MasterPage', $page);
        }  

        
        /**
         * Выводит список предметов по складу
         * @param type $sklad склад
         */
        public function ItemList($sklad = NULL, $perPage = 100, $limit = 0)
        {
            $this->load->library('pagination');
            $this->load->library('form_validation');
            $this->load->helper('form'); 
            $this->load->helper('mylib');
            $this->load->model('itemgroup_model');
           
            $this->form_validation->set_rules('name','Наименование', 'trim|max_lenght[150]');
            $this->form_validation->set_rules('key','Код', 'trim|numeric|max_lenght[8]');
            
            $config['base_url'] = '/sklad/item/ItemList/'.$sklad.'/'.$perPage;
            $config['per_page'] = $perPage;//$this->input->post('perPage')*50+($this->input->post('perPage')+1)*50;
            $config['uri_segment'] = 5;
            
            $_ar = ResultToArray($this->itemgroup_model->aList());
            $_ar['none'] = '';
            
            $data['sklad'] = $sklad;
            $data['cat'] = $_ar;
            
            if ($this->form_validation->run() == FALSE)
            {
                $config['total_rows'] = $this->Item_model->ItemCount($sklad);
                $data['items'] = $this->Item_model->ItemsList($sklad, $limit, $perPage);
                
            }
            else
            {
                $config['total_rows'] = $this->Item_model->ItemCountSearch(
                        $sklad, 
                        $this->input->post('key'),
                        $this->input->post('name'),
                        $this->input->post('category')
                        );
                $data['items'] = $this->Item_model->ItemsSearch(
                        $sklad, 
                        $limit,
                        $this->input->post('key'),
                        $this->input->post('name'),
                        $this->input->post('category'),
                        $perPage
                        );
            }

         
            $this->pagination->initialize($config);
            $data['links'] = $this->pagination->create_links();
            
            $page['content'] = $this->load->view('Items/ItemList', $data, TRUE);
            $this->load->view('MasterPage', $page);
        }
        
        /**
         * Добавление предмета в систему
         */
        public function add()
        {
            $this->load->library('form_validation');
            $this->form_validation->set_rules('itemName','itemName', 'trim|required|max_lenght[150]');
            $this->form_validation->set_rules('buy_count','buy_count', 'trim|required|numeric|max_lenght[15]');
            $this->form_validation->set_rules('measure','measure', 'trim|required|max_lenght[5]');
            $this->form_validation->set_rules('buy_date','measure', 'trim|required|max_lenght[5]|callback_IsDate');
            
            if ($this->form_validation->run() == FALSE)
            {
                $this->load->model('cagent_model');
                $this->load->model('itemgroup_model');
                $this->load->model('objects_model');
                $this->load->helper('mylib');
                
                $this->datacard['cagents'] = ResultToArray($this->cagent_model->aList());
                $this->datacard['groups'] = ResultToArray($this->itemgroup_model->aList());
                $this->datacard['objects'] = $this->objects_model->GetObjectsArray(NULL, FALSE);
                $page['content'] = $this->load->view('Items/ItemAdd', $this->datacard, TRUE);
            }
            else
            {
                $this->load->helper('date');
                //$obj = $this->Objects_model->GetObject(array('id' => $this->input->post('object_id')));
                $data = array(
                    'id'            => 0,
                    'name'          => $this->input->post('itemName'),
                    'group_id'      => $this->input->post('group_id'),
                    'comments'      => $this->input->post('comments'),
                    'contragent_id' => $this->input->post('contragent_id'),
                    'buy_price'     => $this->input->post('buy_price'),
                    'buy_count'     => $this->input->post('buy_count'),
                    'measure'       => $this->input->post('measure'),
                    'buy_date'      => $this->input->post('buy_date'),
                );
                $wh_id = $this->input->post('wh_id');
                $_id = $this->Item_model->SaveItem($data, $wh_id);
                redirect('item/card/'.$_id);
            }
            $this->load->view('MasterPage', $page);
        }
        
        /**
         *
         * @param string $str 
         * @return bool TRUE/FALSE - Является ли стркоа датой 
         */
        function IsDate($str)
        {
            if (strtotime($str))
                return TRUE;
            else
                return FALSE;
        }
                /**
         * Проверка для валидации данных с формы. Проверяет можно ли списать такое количество товара
         * @param type $str строка с поля
         * @return boolean результат проверки
         */
        function checkMax($str)
        {
            $_count = $str;
            $res = TRUE;
            //echo $_count;
            //print_r($this->datacard);
           
            echo 'm ';
            //print_r($this->datacard['fromSklad']['id']);//var_dump((int)$this->datacard['fromSklad']['id']);
            //Получение количества на складе откуда перемещаем
            $_onSklad = 0;
            foreach ($this->datacard['whereIt'] as $s)
            {
                if ((int)$this->datacard['fromSklad']['id'] == (int)$s->objID)
                    $_onSklad = $s->onSklad;
            }
            if ($_count > 0)
            { 
                if ($_count > $_onSklad) 
                {
                    $this->form_validation->set_message('checkMax', 'На складе столько нет');
                    $res = FALSE;
                }
            }
            else
            {
                $this->form_validation->set_message('checkMax', 'Слишком мало предметов для перемещения');
                $res = FALSE;
            }
            return $res;
        }
        
}

